import React, { createContext, useState } from "react";
import { MenuItemProps } from './menuItem'
import ClassNames from "classnames";

type ModeType = "horizontal" | "vertical";
type SelectCallback = (index: string) => void;

export interface MenuProps {
  defaultIndex?: string;
  className?: string;
  mode?: ModeType;
  style?: React.CSSProperties;
  onSelect?: SelectCallback;
}

interface ImenuContent {
  index: string;
  onSelect?: SelectCallback;
  mode? : ModeType ,
}
export const MenuContext = createContext<ImenuContent>({ index: '0' });

const Menu: React.FC<MenuProps> = (props) => {
  const { defaultIndex, mode, style, className, children, onSelect } = props;
  const [currentActive, setActive] = useState(defaultIndex);
  const classes = ClassNames("menu", className, {
    "menu-vertical": mode === "vertical",
    "menu-horizontal" :mode !== "vertical"
  });

  const handleClick = (index: string) => {
    setActive(index);
    if (onSelect) {
      onSelect(index);
    }
  };

  const passedContext: ImenuContent = {
    index: currentActive ? currentActive : '0',
    onSelect: handleClick,
    mode : mode
  };

  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<MenuItemProps>;
      const name = childElement.type.displayName
      if(name === 'MenuItem' || name === 'SubMenu'){
        return React.cloneElement(childElement, {index:index.toString()})
      }else{
        console.warn('Menu children must be a MenuItem')
      }
    })
  }

  return (
    <ul className={classes} style={style} data-testid="test-menu">
      <MenuContext.Provider value={passedContext}>
        {renderChildren()}
      </MenuContext.Provider>
    </ul>
  );
};

Menu.defaultProps = {
  defaultIndex: '0',
  mode: "horizontal",
};

export default Menu;
